"""
商品全部评价独立页面
显示指定商品的所有评价，支持排序：最新/最早/评分高/评分低
"""

import tkinter as tk
from tkinter import ttk
import customtkinter
from ui.pages.scrollable_page import ScrollablePage
from ui.components.review_card import ReviewCard
from ui.styles.theme import Theme
from core.utils.logger import info, error, debug


class ProductReviewsPage(ScrollablePage):
    """商品全部评价页面"""

    def __init__(self, parent, controller):
        self.product_id = None
        self.product_name = ""
        self.sort_by = tk.StringVar(value='newest')
        self.reviews = []
        super().__init__(parent, controller)

    def create_widgets(self):
        content = self.scrollable_frame

        # 顶部栏
        top_bar = customtkinter.CTkFrame(content, fg_color="transparent")
        top_bar.pack(fill='x', padx=20, pady=(10, 10))

        # 返回按钮
        back_btn = customtkinter.CTkButton(
            top_bar,
            text="← Back",
            width=90,
            command=self._back_to_product
        )
        back_btn.pack(side='left')

        # 标题（如果有product_name，显示它）
        title_text = f"{self.product_name} - All Reviews" if self.product_name else "All Reviews"
        self.title_label = customtkinter.CTkLabel(
            top_bar,
            text=title_text,
            font=('Arial', 18, 'bold'),
            text_color=Theme.get_color('fg_primary')
        )
        self.title_label.pack(side='left', padx=12)

        # 排序控件
        sort_frame = customtkinter.CTkFrame(top_bar, fg_color="transparent")
        sort_frame.pack(side='right')

        customtkinter.CTkLabel(
            sort_frame,
            text="Sort:",
            font=('Arial', 11)
        ).pack(side='left', padx=(0, 6))

        self.sort_menu = ttk.Combobox(
            sort_frame,
            values=[
                'newest',    # 最新
                'oldest',    # 最早
                'highest',   # 评分高
                'lowest'     # 评分低
            ],
            state='readonly',
            width=10,
            textvariable=self.sort_by
        )
        self.sort_menu.pack(side='left')
        self.sort_menu.bind('<<ComboboxSelected>>', lambda e: self._reload_reviews())

        # 分割线
        customtkinter.CTkFrame(content, height=2, fg_color=Theme.get_color('border_color')).pack(fill='x', padx=20)

        # 列表容器
        self.list_container = customtkinter.CTkFrame(content, fg_color="transparent")
        self.list_container.pack(fill='both', expand=True, padx=20, pady=15)

    def set_product(self, product_id: str, product_name: str = ""):
        """设置当前查看的商品"""
        if not product_id:
            error("Cannot set product: product_id is None")
            return
        
        self.product_id = product_id
        self.product_name = product_name or product_id
        
        # 更新标题（如果已创建）
        try:
            if hasattr(self, 'title_label'):
                self.title_label.configure(text=f"{self.product_name} - All Reviews")
        except (AttributeError, tk.TclError) as e:
            error(f"Failed to update title label: {e}")
            # 如果title_label还没创建，会在create_widgets中设置
        
        # 重新加载评价
        self._reload_reviews()

    def _reload_reviews(self):
        """按当前排序加载评价并渲染"""
        # 清空现有
        for w in self.list_container.winfo_children():
            w.destroy()

        if not self.product_id:
            error("Cannot reload reviews: product_id is None")
            self._render_empty()
            return

        try:
            info(f"Loading reviews for product: {self.product_id}, sort_by: {self.sort_by.get()}")
            self.reviews = self.controller.review_service.get_product_reviews(
                self.product_id, sort_by=self.sort_by.get()
            )
            info(f"Loaded {len(self.reviews)} reviews for {self.product_id} sorted by {self.sort_by.get()}")
        except Exception as e:
            error(f"Failed to load reviews: {e}")
            import traceback
            error(f"Exception stack: {traceback.format_exc()}")
            self._render_error(f"加载评价失败: {e}")
            return

        if not self.reviews:
            self._render_empty()
            return

        # 使用 ReviewCard 渲染
        # 使用可滚动容器（页面本身已是可滚动）直接平铺
        try:
            for i, review in enumerate(self.reviews):
                try:
                    card = ReviewCard(self.list_container, review)
                    card.pack(fill='x', pady=(0 if i == 0 else 10, 0))
                    info(f"Rendered review card {i+1}/{len(self.reviews)}: {review.review_id[:8]}...")
                except Exception as e:
                    error(f"Failed to render review card {i+1}: {e}")
                    import traceback
                    error(f"Exception stack: {traceback.format_exc()}")
                    # 继续渲染其他评价
                    continue
            info(f"Successfully rendered {len(self.reviews)} review cards")
        except Exception as e:
            error(f"Failed to render review cards: {e}")
            import traceback
            error(f"Exception stack: {traceback.format_exc()}")
            self._render_error(f"渲染评价失败: {e}")

    def _render_empty(self):
        """显示无评价信息"""
        label = customtkinter.CTkLabel(
            self.list_container,
            text="💭 暂无评价，成为第一个评价的用户吧！",
            font=('Arial', 14),
            text_color=Theme.get_color('fg_tertiary')
        )
        label.pack(pady=40)
    
    def _render_error(self, error_message: str):
        """显示错误信息"""
        error_label = customtkinter.CTkLabel(
            self.list_container,
            text=f"❌ {error_message}",
            font=('Arial', 14),
            text_color='#E74C3C'
        )
        error_label.pack(pady=40)

    def _back_to_product(self):
        if not self.product_id:
            return
        self.controller.show_page('ProductDetailPage', product_id=self.product_id)

    def update_data(self):
        """更新页面数据（页面被显示时调用）"""
        try:
            # 页面被显示时刷新（保持当前排序）
            if self.product_id:
                info(f"Updating ProductReviewsPage data for product: {self.product_id}")
                self._reload_reviews()
            else:
                # 如果没有设置product_id，清空显示
                for w in self.list_container.winfo_children():
                    w.destroy()
                info("ProductReviewsPage: No product_id set, cleared display")
        except Exception as e:
            error(f"Failed to update ProductReviewsPage data: {e}")
            import traceback
            error(f"Exception stack: {traceback.format_exc()}")


